package com.example.dao;
import com.example.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("frindDaoImpl") //@Service为给类增加别名
public class FriendDaoImpl implements FriendDao{
    @Autowired //是用在JavaBean中的注解，通过byType形式，用来给指定的字段或方法注入所需的外部资源。
    private JdbcTemplate jdbcTemplate; //jdbc连接工具类
    @Override
    public List<UserBean> findAllFriendsByUsername(String username) {
        String sql = "select id from user where username=?";
        Object[] params = new Object[]{username};
        List<Integer> list=jdbcTemplate.queryForList(sql, Integer.class,params);
        Integer id=list.get(0);
        Object[] params2 = new Object[]{id};
        String sql2 = "select * from user where id in (select friendsId from friend where userid=?)";
        return jdbcTemplate.query(
                sql2,
                params2,
                new BeanPropertyRowMapper<UserBean>(UserBean.class));
    }
    @Override
    public boolean addFriend(String username,String friendname){
        String sql = "select id from user where username=?";
        Object[] params1 = new Object[]{username};
        Object[] params2 = new Object[]{friendname};
        Integer id=jdbcTemplate.queryForObject(sql, Integer.class,params1);
        Integer id2=jdbcTemplate.queryForObject(sql, Integer.class,params2);
        String sql2 = "insert into friend(userId,friendsId)values(?,?)";
        Object[] params3 = {id,id2};
        return jdbcTemplate.update(sql2, params3)>0;
    }
    @Override
    public boolean deleteFriend(String username,String friendname){
        String sql = "select id from user where username=?";
        Object[] params1 = new Object[]{username};
        Object[] params2 = new Object[]{friendname};
        Integer id=jdbcTemplate.queryForObject(sql, Integer.class,params1);
        Integer id2=jdbcTemplate.queryForObject(sql, Integer.class,params2);
        String sql2 = "delete from friend where userId=? and friendsId=?";
        Object[] params3 = {id,id2};
        return jdbcTemplate.update(sql2, params3)>0;
    }


}
